package dao

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"grpc-todoList/app/user/internal/repository/db/model"
	userPb "grpc-todoList/idl/pb/user"
	"grpc-todoList/pkg/util/logger"
)

type UserDao struct {
	*gorm.DB
}

func NewUserDao(ctx context.Context) *UserDao {
	return &UserDao{NewDBClient(ctx)}
}

func NewUserDaoByDB(db *gorm.DB) *UserDao {
	return &UserDao{db}
}

// GetUserInfo 获取用户信息
func (dao *UserDao) GetUserInfo(req *userPb.UserRequest) (user *model.User, err error) {
	err = dao.DB.Model(&model.User{}).Where("username = ?", req.Username).First(&user).Error
	return
}

// CreateUser 用户创建
func (dao *UserDao) CreateUser(req *userPb.UserRequest) (err error) {
	var count int64
	dao.DB.Model(&model.User{}).Where("username = ?", req.Username).Count(&count)
	if count != 0 {
		return errors.New("user already exists")
	}

	user := &model.User{
		Username: req.Username,
		Nickname: req.Nickname,
	}
	_ = user.SetPassword(req.Password)
	err = dao.DB.Model(&model.User{}).Create(&user).Error
	if err != nil {
		logger.LoggersObj.Error("Create User Error:" + err.Error())
		return
	}
	return
}
